/**
 * @author cqb 2016-06-23.
 * @module MessageBox
 */

const React = require("react");
const ReactDOM = require('react-dom');
const classnames = require("classnames");
const BaseComponent = require("core/BaseComponent");
const Dom = require('utils/Dom');
const PropTypes = React.PropTypes;
const Panel = require('Panel');
const Button = require('Button');
const velocity = require("velocity");

/**
 * MessageBox 类
 * @class MessageBox
 * @constructor
 * @extend BaseComponent
 */
class MessageBox extends BaseComponent {
    static defaultProps = {
        title: '',
        msg: '',
        visibility: false,
        type: 'info',
        confirmText: '确 定',
        cancelText: '取 消',
        confirmTheme: 'primary',
        cancelTheme: 'default',
        confirmIcon: 'check',
        cancelIcon: 'close',
        draggable: true,
        loading: false
    };

    constructor(props) {
        super(props);

        this.addState({
            title: props.title,
            msg: props.msg,
            visibility: false,
            type: props.type
        });

        let confirmText = props.confirmText;
        let cancelText = props.cancelText;

        let confirmTheme = props.confirmTheme;
        let cancelTheme = props.cancelTheme;

        let confirmIcon = props.confirmIcon;
        let cancelIcon = props.cancelIcon;

        if(props.footers) {
            this.footers = props.footers;
        }else{
            this.confirm = this.confirm.bind(this);
            this.cancle = this.cancle.bind(this);

            let components = [<Button theme={confirmTheme} raised={true} icon={confirmIcon} onClick={this.confirm} ref={(f) => this.okBtn = f}>{confirmText}</Button>];
            if (props.type === "confirm") {
                components.push(<Button theme={cancelTheme} raised={true} icon={cancelIcon} className="ml-10" onClick={this.cancle}>{cancelText}</Button>);
            }
            this.footers = {
                components: components
            };
        }

        this.backdrop = null;

        //保存的数据
        this.data = null;

        this.panel = null;
    }

    setData(data){
        this.data = data;
    }

    getData(){
        return this.data;
    }

    /**
     * 显示loading
     */
    showLoading () {
        if (this.okBtn) {
            this.okBtn.setLoading(true);
        }
    }

    /**
     * 隐藏loading
     */
    hideLoading () {
        if (this.okBtn) {
            this.okBtn.setLoading(false);
        }
    }

    cancle(){
        if(this.state.type === "confirm" && this.props.confirm){
            this.props.confirm.apply(this, [false]);
            this.hide();
        }else{
            this.hide();
        }
    }

    hide(){
        velocity(this.container, "fadeOut", { duration: 300 });

        if(this.props.onHide){
            this.props.onHide();
        }
        this.emit("hide");

        let count = this.backdrop.getAttribute('data-count');
        count = count - 1;
        this.backdrop.setAttribute('data-count', count);
        if (count === 0) {
            this.backdrop.style.display = 'none';
            Dom.dom(Dom.query('body')).removeClass('modal-open');
        }
    }

    confirm(){
        let confirm = this.props.confirm || (this.listeners("confirm").length ? this.listeners("confirm")[0] : null);
        if(confirm){
            if(this.state.type === "confirm") {
                if (confirm.apply(this, [true])) {
                    this.hide();
                }
            }else{
                confirm.apply(this, []);
                this.hide();
            }
        }else{
            this.hide();
        }
    }

    show(msg, title){
        // this.setState({
        //     title: this.state.title || title,
        //     msg: msg,
        //     visibility: true
        // });

        this.panel.setTitleAndContent(this.state.title || title, this.state.msg || msg);

        if(!this.backdrop){
            let ele = Dom.query(".shadow-backdrop");
            if(ele){
                this.backdrop = ele;
            }else {
                this.backdrop = document.createElement("div");
                this.backdrop.setAttribute("class", "shadow-backdrop");
                document.body.appendChild(this.backdrop);
            }
        }

        this.backdrop.style.display = "block";
        let count = this.backdrop.getAttribute('data-count');
        count = count == null ? 1 : parseInt(count, 10) + 1;
        if (this.container.style.display === 'none') {
            this.backdrop.setAttribute('data-count', count);
        }
        Dom.dom(Dom.query('body')).addClass('modal-open');

        window.setTimeout(()=>{
            let ele = ReactDOM.findDOMNode(this.panel);
            Dom.dom(this.container).show();
            const h = ele.clientHeight;
            const w = ele.clientWidth;
            const viewWidth = document.documentElement.clientWidth;
            const viewHeight = document.documentElement.clientHeight;
            const pos = {
                x: (viewWidth - w) / 2,
                y: (viewHeight - h) / 2
            };
            if (h > viewHeight) {
                pos.y = 10;
            }
            this.panel.setPosition(pos);

            // let w = ele.clientWidth;
            // let h = ele.clientHeight;
            // ele.style.marginLeft = -w/2+"px";
            // ele.style.marginTop = -h/2+"px";
            Dom.dom(this.container).show();
            velocity(this.container, "fadeIn", { duration: 300 });

            if(this.props.onShow){
                this.props.onShow();
            }
            this.emit("show");
        }, 0);
    }

    componentDidMount(){
        this.container = document.createElement("div");
        document.body.appendChild(this.container);
        Dom.dom(this.container).addClass("cm-popup-warp");
        Dom.dom(this.container).hide();

        let {className, style} = this.props;
        className = classnames("cm-messageBox", className, this.state.type);
        let props = Object.assign({}, this.props);
        props.className = className;

        props.footers = this.footers;
        style = Object.assign({}, style);
        props.style = style;

        ReactDOM.render(<Panel ref={(ref)=>{this.panel = ref;}} {...props} content={this.state.msg}></Panel>, this.container);
    }

    render(){
        return (
            <div></div>
        );
    }
}

MessageBox.propTypes = {
    /**
     * 标题
     * @attribute title
     * @type {String}
     */
    title: PropTypes.string,
    /**
     * 信息
     * @attribute msg
     * @type {String}
     */
    msg: PropTypes.string,
    /**
     * 类型
     * @attribute type
     * @type {String}
     */
    type: PropTypes.oneOf(["info", "confirm", "error", "warning"]),
    /**
     * 自定义class
     * @attribute className
     * @type {String}
     */
    className: PropTypes.string,
    /**
     * 自定义样式
     * @attribute style
     * @type {Object}
     */
    style: PropTypes.object
};

module.exports = MessageBox;
